<?php
namespace app\admin\middleware;

use app\model\RoutesApi;

class ApiAuth{
    public function handle($request, \Closure $next)
    {
        $paths = explode('/', $request->pathinfo());
        $controller = $paths[0] ?? 'index';
        $action = isset($paths[1]) ? ($paths[1] ?: 'index'): 'index';
        $ra = RoutesApi::where(['module'=>'admin','controller'=>$controller, 'action'=>$action])->find();
        if($ra && $ra->need_login){            //需登录
            if(!$request->user){
                throw new \Exception('请登录');
            }
            if($request->user->role->id != 1 && !in_array($ra->id, $request->user->role->routes_api_ids)){
                throw new \Exception('无权限');
            }
        }
        $rep = $next($request);
        return $rep;
    }
}